package com.yhwch.fun.utils;

import com.yhwch.fun.domain.FilePathPojo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Executable;

public class FileUtil {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 读取首行内容
     * @param filePath 文件绝对路径
     * @return
     */
    public static String readFirstRow(String filePath,String charSet){
        BufferedReader buffer = null;
        String back ;
        try{
            File file=new File(filePath);
            if(file.exists()){
                FileInputStream in = new FileInputStream(file);
                InputStreamReader read = new InputStreamReader(in, charSet);//ANSI 可以不转码或者用GBK转码，其他需要相应格式转码
                buffer = new BufferedReader(read);
                while ((back = buffer.readLine()) != null){
                    //只读取一次即返回
                    log.info("首行读取成功,内容:【{}】",back);
                    break;
                }
            }else{
                back = "noFile";
            }
        }catch (Exception e){
            log.error("首行内容获取失败,文件:{},异常信息{}",filePath,e);
            back = "exception";
        }finally {
            if(buffer!=null){
                try {
                    buffer.close();
                }catch (IOException e) {
                    log.error("关闭流异常,文件:{},异常信息{}",filePath,e);
                }
            }
        }
        return back;
    }

    /**
     * 读取文件尾行内容
     * @param filePath 文件绝对路径
     * @return
     */
    public static String readLastRow(String filePath,String charSet){
        RandomAccessFile raf = null;
        String lastLine = "";
        try {
            raf = new RandomAccessFile(filePath, "r");
            long len = raf.length();
            if (len != 0L) {
                long pos = len - 1;
                while (pos > 0) {
                    pos--;
                    raf.seek(pos);
                    if (raf.readByte() == '\n') {
                        lastLine = raf.readLine();
                        lastLine = new String(lastLine.getBytes("8859_1"), charSet);
                        log.info("尾行读取成功,内容:【{}】",lastLine);
                        break;
                    }
                }
            }
        }catch (Exception  e){
            log.error("读取最后一行异常,文件:{},原因:{}",filePath,e);
        }finally {
            if(raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    log.error("关闭流异常,文件:{},原因:{}",filePath,e);
                }
            }
        }
        return lastLine;
    }

    /**
     * 将首行修改为 空格
     * @param filePath
     * @param info
     * @return
     */
    public static boolean modifyFirstRow(String filePath,String info){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(filePath, "rw");

            StringBuilder sbu = new StringBuilder();
            for(int i=0;i<info.length();i++){
                sbu.append("A");
            }
            byte[] b = sbu.toString().getBytes();
            raf.seek(0);
            raf.write(b,0,b.length);
            return true;
        }catch (Exception  e){
            log.error("修改文件内容异常,文件:{},内容:{},原因:{}",filePath,info,e);
        }finally {
            if(raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    log.error("关闭流异常,文件:{},原因:{}",filePath,e);
                }
            }
        }
        return false;
    }
    /**
     * 末尾追加内容
     * @param filePath
     * @param info
     * @return
     */
    public static boolean modifyLastRow(String filePath,String info){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(filePath, "rw");
            long len = raf.length();
            raf.seek(len);
            raf.write(info.getBytes());
            return true;
        }catch (Exception  e){
            log.error("修改文件内容异常,文件:{},内容:{},原因:{}",filePath,info,e);
        }finally {
            if(raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    log.error("关闭流异常,文件:{},原因:{}",filePath,e);
                }
            }
        }
        return false;
    }

    public static boolean gbkToUtf8(String filePath,String newFilePath){
        File file=new File(filePath);
        if(!file.exists()){
            log.info("gbkToUtf8 fail,文件不存在{}",file);
            return false;
        }
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            long s = System.currentTimeMillis();
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file), "GBK"));
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(newFilePath), "UTF-8"));
            String line = null;
            int k = 0;
            while ((line = reader.readLine()) != null ) {
                writer.write(line);
                writer.newLine();
                k++;
                if(k >= 100000){
                    writer.flush();
                }
            }
            writer.flush();
            long e = System.currentTimeMillis();
            log.info("gbkToUtf8 完成,耗时:{},新文件:{}",e-s,newFilePath);
            return true;
        }catch (Exception e){
            log.error("gbkToUtf8 exception,{},e=",file,e);
        }finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
            }catch (Exception e){
                log.error("关闭异常,e=",e);
            }
        }
        return false;
    }
}